<?php
namespace app\index\controller;

use think\Controller;
use think\View;
use Des3\DES3;

class Login extends Controller {

    public function index() {
        if (request()->isAjax()) {
            $des = new DES3();
            $param = [
                'mobile' => $des->encrypt(input('param.mobile', '')),
                'code' => input('param.code', ''),
                'type' => 2  // 微信端只有验证码登录
            ];
            $data = local_invoke_api('Login', $param);
            if ($data['code'] == 200) {
                // 绑定微信
                $save_data = [
                    'openid' => session('openid')
                ];

                model('member')->save($save_data, ['id' => $data['data']['member_id']]);

                // 登录成功  记录session
                session('member_id', $data['data']['member_id']);
                session('member_username', input('param.mobile', ''));

                // 更新头像和昵称
                model('member_role_info')->save(['nickname' => session('nickname'), 'headimgurl' => session('headimgurl')], ['member_id' => $data['data']['member_id']]);
            }
            $data['url'] = session('login_base_url');
            return json($data);
        } else {
            $login_base_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : url('member/index');
            session('login_base_url', $login_base_url);
            if (!session('?openid')) {
                $common = new Common();
                $common->oauth();  // 获取授权
            }
            return view();
        }
    }

    public function check_phone() {
        $data = local_invoke_api('check_phone', ['username' => input('param.mobile')]);
        return json($data);
    }
}
